package com.snail.config;// WebSocketConfig.java


import com.snail.handler.OnlineUserWebSocketHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * WebSocket配置类，用于配置和注册WebSocket处理器
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    private final OnlineUserWebSocketHandler onlineUserWebSocketHandler;

    /**
     * 构造函数，注入OnlineUserWebSocketHandler实例
     *
     * @param onlineUserWebSocketHandler 在线用户WebSocket处理器
     */
    public WebSocketConfig(OnlineUserWebSocketHandler onlineUserWebSocketHandler) {
        this.onlineUserWebSocketHandler = onlineUserWebSocketHandler;
    }

    /**
     * 注册WebSocket处理器，配置WebSocket端点和跨域设置
     *
     * @param registry WebSocket处理器注册中心
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        //将onlineUserWebSocketHandler处理器映射到"/ws/online"路径 客户端可以通过ws://服务器地址/ws/online建立WebSocket连接
        registry.addHandler(onlineUserWebSocketHandler, "/ws/online")
                .setAllowedOrigins("*"); //允许所有来源的跨域请求
    }
}
